package com.lekang.system.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.system.domain.OrderManagement;
import com.lekang.system.service.IOrderManagementService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 订单管理Controller
 * 
 * @author zhihao
 * @date 2025-10-15
 */
@RestController
@RequestMapping("/system/order_management")
public class OrderManagementController extends BaseController
{
    @Autowired
    private IOrderManagementService orderManagementService;

    /**
     * 查询订单管理列表
     */
//    @PreAuthorize("@ss.hasPermi('system:ordermanagement:list')")
    @GetMapping("/list")
    public TableDataInfo list(OrderManagement orderManagement)
    {
        startPage();
        List<OrderManagement> list = orderManagementService.selectOrderManagementList(orderManagement);
        return getDataTable(list);
    }

    /**
     * 导出订单管理列表
     */
//    @PreAuthorize("@ss.hasPermi('system:ordermanagement:export')")
//    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderManagement orderManagement)
    {
        List<OrderManagement> list = orderManagementService.selectOrderManagementList(orderManagement);
        ExcelUtil<OrderManagement> util = new ExcelUtil<OrderManagement>(OrderManagement.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:ordermanagement:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(orderManagementService.selectOrderManagementById(id));
    }

    /**
     * 新增订单管理
     */
//    @PreAuthorize("@ss.hasPermi('system:ordermanagement:add')")
//    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OrderManagement orderManagement)
    {
        return toAjax(orderManagementService.insertOrderManagement(orderManagement));
    }

    /**
     * 修改订单管理
     */
//    @PreAuthorize("@ss.hasPermi('system:ordermanagement:edit')")
//    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OrderManagement orderManagement)
    {
        return toAjax(orderManagementService.updateOrderManagement(orderManagement));
    }

    /**
     * 删除订单管理
     */
//    @PreAuthorize("@ss.hasPermi('system:ordermanagement:remove')")
//    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(orderManagementService.deleteOrderManagementByIds(ids));
    }


    /**
     * 根据三个字段更新订单状态和交易状态
     * 用于：支付超时关闭订单、或其他需要精准定位的场景
     */
    @RequestMapping("/update-by-three-fields")
    public AjaxResult updateByThreeFields(
            @RequestBody OrderManagement order // 直接使用现有实体类接收JSON参数
    ) {
        // 从order中提取所需参数
        Long elderlyId = order.getElderlyId();
        Long nursingItemId = order.getNursingItemId();
        Date expectedServiceTime = order.getExpectedServiceTime();
        String orderStatus = order.getOrderStatus();
        String transactionStatus = order.getTransactionStatus();

        // 校验核心参数是否存在
        if (elderlyId == null || nursingItemId == null || expectedServiceTime == null) {
            return AjaxResult.error("老人ID、护理项目ID、服务时间不能为空");
        }

        // 调用Service执行更新
        int rows = orderManagementService.updateOrderStatusByThreeFields(
                elderlyId,
                nursingItemId,
                expectedServiceTime,
                orderStatus,
                transactionStatus
        );

        if (rows == 1) {
            return AjaxResult.success("订单状态更新成功");
        } else if (rows == 0) {
            return AjaxResult.error("未找到匹配的订单（老人ID、项目ID、服务时间可能不匹配）");
        } else {
            return AjaxResult.error("系统异常，影响行数异常：" + rows);
        }
    }

    /**
     * 根据老人外键ID查询订单列表
     */
    @GetMapping("/list-by-elderly/{elderlyId}")
    public TableDataInfo listByElderlyId(@PathVariable("elderlyId") Long elderlyId) {
        startPage();
        OrderManagement orderManagement = new OrderManagement();
        orderManagement.setElderlyId(elderlyId);
        List<OrderManagement> list = orderManagementService.selectOrderManagementList(orderManagement);
        return getDataTable(list);
    }
}
